package com.gzz.manage.sys.dept;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @类说明 【组织机构】业务逻辑层
 * @author 高振中
 * @date 2020-11-15 21:39:55
 **/
@Service
public class DeptService {

	@Autowired
	private DeptDao deptDao; // 注入【组织机构】数据访问层

	/**
	 * @方法说明 【功能菜单】树
	 */
	public List<Dept> tree() {
		DeptCond cond = DeptCond.builder().build();
		cond.setOrders("id");
		List<Dept> depts = deptDao.list(Dept.class, cond);
		Map<Integer, Dept> treeMap = new HashMap<>();
		List<Dept> treeList = new ArrayList<>();
		for (Dept dept : depts) {
			treeMap.put(dept.getId(), dept);
			if (dept.getParentId() == 0) {
				treeList.add(dept);
			} else {
				if (treeMap.get(dept.getParentId()).getChildren() == null)
					treeMap.get(dept.getParentId()).setChildren(new ArrayList<>());
				treeMap.get(dept.getParentId()).getChildren().add(dept);// children
			}
		}
		treeMap.clear();
		return treeList;
	}

	/**
	 * @方法说明 【组织机构】新增
	 */
	@Transactional
	public int save(Dept dept) {
		dept.setLeaf(Byte.valueOf("1"));
		if (!dept.getParentId().equals(0))
			deptDao.updateParentSave(dept.getParentId());
		return deptDao.save(dept);
	}

	/**
	 * @方法说明 【组织机构】删除
	 */
	@Transactional
	public int delete(Object[] ids) {
		List<Dept> depts = deptDao.list(Dept.class, DeptCond.builder().ids(ids).build());
		int count = deptDao.delete(Dept.class, ids);
		depts.forEach(dept -> deptDao.updateParentDelete(dept.getParentId()));
		return count;
	}

	/**
	 * @方法说明 【组织机构】更新
	 */
	public int update(Dept dept) {
		return deptDao.update(dept);
	}

	/**
	 * @方法说明 【组织机构】列表
	 */
	public List<Dept> list(DeptCond cond) {
		return deptDao.list(Dept.class, cond);
	}
}